<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @drag-sort="sortTable"
    >
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- usernameHeader -->
      <template #usernameHeader="scope">
        <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
          {{ scope.column.label }}
        </el-button>
      </template>
      <!-- createTime -->
      <template #createTime="scope">
        <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
          {{ scope.row.createTime }}
        </el-button>
      </template>
    </ProTable>
    <el-dialog v-model="dialogVisible" title="源数据" width="500" :align-center="true">
      <div style="max-height: 500px; overflow: auto">{{ dialogContent }}</div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive } from "vue";
import { User } from "@/api/interface";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { getWarningList } from "@/api/modules/datawarn";
import ShowChileDate from "@/components/ShowChileDate/index.vue";
import dayjs from "dayjs";
// ProTable 实例
const route = useRoute();
const dialogVisible = ref(false);
const dialogContent = ref("");
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.list,
    total: data.total
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  let startTime: any = undefined;
  let endTime: any = undefined;
  if (newParams.createTime && newParams.createTime.length > 0) {
    startTime = dayjs(newParams.createTime[0]).unix();
    endTime = dayjs(newParams.createTime[1]).unix();
    delete newParams.createTime;
  }
  let paramsType: number = 3;
  if (route.query.type) {
    paramsType = Number(route.query.type);
  }
  if (proTable.value?.searchParam.type) {
    paramsType = proTable.value?.searchParam.type;
  }
  const pageParams = {
    ...proTable.value?.searchParam,
    type: paramsType,
    startTime: startTime,
    endTime: endTime,
    limit: newParams.pageSize,
    page: newParams.pageNum
  };
  return getWarningList(pageParams);
};
const handleViewDataBox = data_box => {
  dialogVisible.value = true;
  dialogContent.value = data_box;
};
// 表格配置项
const columns = reactive<ColumnProps<User.ResUserList>[]>([
  // { type: "selection", fixed: "left", width: 70 },
  // { type: "sort", label: "Sort", width: 80 },
  // { type: "expand", label: "Expand", width: 85 },
  {
    prop: "shop_name",
    label: "店铺名称",
    width: 100,
    search: {
      // 自定义 search 显示内容
      render: ({ searchParam }) => {
        return (
          <div class="flex-center">
            <el-input v-model={searchParam.keyword} placeholder="请输入店铺名称" />
          </div>
        );
      }
    }
  },
  {
    prop: "type",
    label: "类型",
    width: 150,
    render: (scope: any) => {
      if (scope?.row?.type === 1) {
        return <el-tag type="success">本月订单数据</el-tag>;
      }
      if (scope.row.type === 2) {
        return <el-tag type="danger">Request失败</el-tag>;
      }
      if (scope.row.type === 3) {
        return <el-tag type="primary">自动同步备份</el-tag>;
      }
      if (scope.row.type === 4) {
        return <el-tag type="warning">结单数据</el-tag>;
      }
      if (scope.row.type === 5) {
        return <el-tag type="danger">Sqlite数据库报错</el-tag>;
      }
      return scope.type;
    },
    search: {
      // 自定义 search 显示内容
      render: ({ searchParam }) => {
        return (
          <div class="flex-center">
            <el-select v-model={searchParam.type} placeholder="请选择类型">
              <el-option key="1" label="本月订单数据" value={1} />
              <el-option key="2" label="Request失败" value={2} />
              <el-option key="3" label="自动同步备份" value={3} />
              <el-option key="5" label="Sqlite数据库报错" value={5} />
            </el-select>
          </div>
        );
      }
    }
  },
  {
    prop: "file_path",
    label: "原数据",
    width: 100,
    render: (scope: any) => {
      if (scope.row.data_box) {
        return (
          <el-button type="primary" size="small" onClick={() => handleViewDataBox(scope.row.data_box)}>
            查看
          </el-button>
        );
      }
      return (
        <el-link href={scope.row.file_path} target="_blank">
          下载
        </el-link>
      );
    }
  },
  {
    prop: "data_box",
    label: "关键参数",
    render: (scope: any) => {
      let params: any = {};
      if (scope.row.data_box) {
        params = JSON.parse(scope.row.data_box);
      }
      let showList: any[] = [];
      if (params.shopId) {
        showList.push({
          label: "店铺ID",
          value: params.shopId
        });
      }
      if (params.osInfo) {
        showList.push({
          label: "语言",
          value: params.osInfo.appLanguage
        });
        showList.push({
          label: "App版本",
          value: params.osInfo.appVersion
        });
        showList.push({
          label: "系统类型",
          value: params.osInfo.osName + " " + params.osInfo.osVersion
        });
        showList.push({
          label: "屏幕信息",
          value: `w:${params.osInfo.windowWidth} h: ${params.osInfo.windowHeight}`
        });
      }
      if (showList.length > 0) {
        return (
          <div className="flex">
            {showList.map((item, index) => {
              return (
                <div key={index}>
                  {item.label}: {item.value}
                </div>
              );
            })}
          </div>
        );
      }
      return "";
    }
  },
  {
    prop: "created_at",
    label: "日期(时区:America/Santiago)",
    search: {
      el: "date-picker",
      span: 1,
      props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" }
    },
    render: (scope: any) => {
      if (scope.row.data_box) {
        let unix = JSON.parse(scope.row.data_box).unix;
        return <ShowChileDate value={unix} />;
      }
      return "";
    }
  }
]);

// 表格拖拽排序
const sortTable = () => {
  ElMessage.success("修改列表排序成功");
};
</script>
